package services

import (
	"hg/enmu"
	"hg/models"
	"hg/pkg/database"
	"hg/pkg/middleware"
	"hg/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 修改用户信息
func UpdateUserinfo(c *gin.Context) {
	user := getUserInfo(c)
	resp := models.GetDefaultResp()
	if err := c.BindJSON(user); err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}
	err := database.UpdateUserinfo(user)
	if err != nil {
		logrus.Error("failed to update userinfo", err)
		return
	}
	token, err := middleware.CreateToken(user)
	if err != nil {
		logrus.Errorln("Token签名失败:", err)
		return
	}
	utils.SetCookie(c, token)
	c.JSON(http.StatusOK, resp)
}

// 修改用户密码
func UpadatePassword(c *gin.Context) {
	resetPassword := new(models.ResetPassword)
	resp := models.GetDefaultResp()
	user := getUserInfo(c)
	if err := c.ShouldBindJSON(&resetPassword); err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}
	// if ok := database.VerifyEmailCode(user, resetPassword.Code); !ok {
	// 	c.String(http.StatusBadRequest, "验证失败")
	// 	return
	// }
	if ok := CheckCodes(user.Username, resetPassword.Code); !ok {
		c.String(http.StatusBadRequest, "验证失败")
		return
	}
	hashedPassword := utils.HashPassword(resetPassword.Password, user.Username)
	user.Password = hashedPassword
	err := database.UpdateUserinfo(user)
	if err != nil {
		logrus.Error("failed to update userinfo", err)
		return
	}
	c.JSON(http.StatusOK, resp)
}

func getUserInfo(c *gin.Context) *models.Userinfo {
	user, exists := c.Get("user")
	if !exists {
		logrus.Println("user not exists")
		return nil
	}
	return user.(*models.Userinfo)
}

func GetUserInfo(c *gin.Context) {
	resp := models.GetDefaultResp()
	videoIDStr := c.Param("int")
	videoID, err := strconv.Atoi(videoIDStr)
	if err != nil {
		logrus.Errorln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid video ID"})
		return
	}
	user, _ := database.GetUserinfoByVideoId(videoID)
	resp.Data = user
	c.JSON(http.StatusOK, resp)
}

func GetUserInfoToTable(c *gin.Context) {
	resp := models.GetDefaultResp()
	user := getUserInfo(c)
	data := new(models.UserinfoToTable)
	data.Id = user.Id
	data.Username = user.Username
	if user.Gender == enmu.Male {
		data.Gender = "男"
	} else if user.Gender == enmu.Female {
		data.Gender = "女"
	} else {
		data.Gender = "保密"
	}
	data.Birth = user.Birth
	data.Region = "未知"
	resp.Data = data
	c.JSON(http.StatusOK, resp)
}
